using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using twistmachinev2.Entity;
using twistmachinev2.Repository;

namespace twistmachinev2
{
    public partial class FrmUserManagement : Form
    {
        private SqliteRepository repository;
        private List<PUser> allUsers;
        private PUser currentUser;
        private bool isEditing = false;

        public FrmUserManagement()
        {
            InitializeComponent();
            repository = new SqliteRepository();
            InitializeForm();
        }

        private void InitializeForm()
        {
            // 初始化权限下拉框
            cmbPermission.Items.Clear();
            cmbPermission.Items.Add(new PermissionItem { Text = "操作员", Value = 30 });
            cmbPermission.Items.Add(new PermissionItem { Text = "管理员", Value = 60 });
            cmbPermission.Items.Add(new PermissionItem { Text = "超级管理员", Value = 90 });
            cmbPermission.DisplayMember = "Text";
            cmbPermission.ValueMember = "Value";

            // 初始化搜索权限下拉框
            cmbSearchPermission.Items.Clear();
            cmbSearchPermission.Items.Add(new PermissionItem { Text = "操作员", Value = 30 });
            cmbSearchPermission.Items.Add(new PermissionItem { Text = "管理员", Value = 60 });
            cmbSearchPermission.Items.Add(new PermissionItem { Text = "超级管理员", Value = 90 });
            cmbSearchPermission.DisplayMember = "Text";
            cmbSearchPermission.ValueMember = "Value";

            // 初始化状态下拉框
            cmbStatus.Items.Clear();
            cmbStatus.Items.Add("启用");
            cmbStatus.Items.Add("停用");

            // 设置DataGridView
            SetupDataGridView();

            // 加载用户数据
            LoadUsers();

            // 初始状态设置
            SetFormMode(FormMode.View);
        }

        private void SetupDataGridView()
        {
            dgvUsers.AutoGenerateColumns = false;
            dgvUsers.AllowUserToAddRows = false;
            dgvUsers.AllowUserToDeleteRows = false;
            dgvUsers.ReadOnly = true;
            dgvUsers.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvUsers.MultiSelect = false;

            dgvUsers.Columns.Clear();

            dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "UserId",
                HeaderText = "用户ID",
                DataPropertyName = "UserId",
                Width = 120
            });

            dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "UserName",
                HeaderText = "用户名",
                DataPropertyName = "UserName",
                Width = 150
            });

            dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "IDCardNo",
                HeaderText = "身份证号",
                DataPropertyName = "IDCardNo",
                Width = 180
            });

            dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "PermissionText",
                HeaderText = "权限",
                DataPropertyName = "PermissionText",
                Width = 100
            });

            dgvUsers.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "UserStatus",
                HeaderText = "状态",
                DataPropertyName = "UserStatus",
                Width = 80
            });
        }

        private void LoadUsers()
        {
            try
            {
                // 这里需要根据实际的Repository实现来调用
                allUsers = repository.GetList<PUser>();
                // 临时模拟数据，实际使用时请替换为真实的数据库查询
                //allUsers = new List<PUser>();

                var usersWithPermissionText = allUsers.Select(u => new
                {
                    u.UserId,
                    u.UserName,
                    u.IDCardNo,
                    u.UserStatus,
                    u.Password,
                    u.Permissionvalue,
                    PermissionText = GetPermissionText(u.Permissionvalue)
                }).ToList();

                dgvUsers.DataSource = usersWithPermissionText;

                lblTotalCount.Text = $"总计: {allUsers.Count} 个用户";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载用户数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetPermissionText(long permissionValue)
        {
            switch (permissionValue)
            {
                case 30: return "操作员";
                case 60: return "管理员";
                case 90: return "超级管理员";
                default: return "未知";
            }
        }

        private void SearchUsers()
        {
            if (allUsers == null) return;

            var filteredUsers = allUsers.AsEnumerable();

            // 按用户ID搜索
            if (!string.IsNullOrWhiteSpace(txtSearchUserId.Text))
            {
                filteredUsers = filteredUsers.Where(u => u.UserId.Contains(txtSearchUserId.Text));
            }

            // 按用户名搜索
            if (!string.IsNullOrWhiteSpace(txtSearchUserName.Text))
            {
                filteredUsers = filteredUsers.Where(u => u.UserName.Contains(txtSearchUserName.Text));
            }

            // 按权限筛选
            if (cmbSearchPermission.SelectedItem != null)
            {
                var selectedPermission = ((PermissionItem)cmbSearchPermission.SelectedItem).Value;
                filteredUsers = filteredUsers.Where(u => u.Permissionvalue == selectedPermission);
            }

            // 按状态筛选
            if (cmbSearchStatus.SelectedIndex >= 0)
            {
                var selectedStatus = cmbSearchStatus.SelectedItem.ToString();
                filteredUsers = filteredUsers.Where(u => u.UserStatus == selectedStatus);
            }

            var result = filteredUsers.Select(u => new
            {
                u.UserId,
                u.UserName,
                u.IDCardNo,
                u.UserStatus,
                u.Password,
                u.Permissionvalue,
                PermissionText = GetPermissionText(u.Permissionvalue)
            }).ToList();

            dgvUsers.DataSource = result;
            lblTotalCount.Text = $"总计: {result.Count} 个用户";
        }

        private void SetFormMode(FormMode mode)
        {
            switch (mode)
            {
                case FormMode.View:
                    isEditing = false;
                    EnableEditControls(false);
                    btnAdd.Enabled = true;
                    btnEdit.Enabled = dgvUsers.SelectedRows.Count > 0;
                    btnDelete.Enabled = dgvUsers.SelectedRows.Count > 0;
                    btnSave.Enabled = false;
                    btnCancel.Enabled = false;
                    break;

                case FormMode.Add:
                    isEditing = true;
                    EnableEditControls(true);
                    ClearEditControls();
                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    txtUserId.Focus();
                    break;

                case FormMode.Edit:
                    isEditing = true;
                    EnableEditControls(true);
                    txtUserId.ReadOnly = true; // 编辑时不允许修改用户ID
                    btnAdd.Enabled = false;
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    txtUserName.Focus();
                    break;
            }
        }

        private void EnableEditControls(bool enabled)
        {
            txtUserId.ReadOnly = !enabled;
            txtUserName.ReadOnly = !enabled;
            txtPassword.ReadOnly = !enabled;
            txtIDCardNo.ReadOnly = !enabled;
            cmbPermission.Enabled = enabled;
            cmbStatus.Enabled = enabled;
        }

        private void ClearEditControls()
        {
            txtUserId.Text = "";
            txtUserName.Text = "";
            txtPassword.Text = "";
            txtIDCardNo.Text = "";
            cmbPermission.SelectedIndex = 0;
            cmbStatus.SelectedIndex = 0;
            currentUser = null;
        }

        private void LoadUserToEdit(PUser user)
        {
            currentUser = user;
            txtUserId.Text = user.UserId;
            txtUserName.Text = user.UserName;
            txtPassword.Text = user.Password;
            txtIDCardNo.Text = user.IDCardNo;

            // 设置权限
            for (int i = 0; i < cmbPermission.Items.Count; i++)
            {
                if (((PermissionItem)cmbPermission.Items[i]).Value == user.Permissionvalue)
                {
                    cmbPermission.SelectedIndex = i;
                    break;
                }
            }

            cmbStatus.SelectedItem = user.UserStatus;
        }

        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(txtUserId.Text))
            {
                MessageBox.Show("请输入用户ID", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUserId.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtUserName.Text))
            {
                MessageBox.Show("请输入用户名", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUserName.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                MessageBox.Show("请输入密码", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPassword.Focus();
                return false;
            }

            if (cmbPermission.SelectedItem == null)
            {
                MessageBox.Show("请选择权限", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbPermission.Focus();
                return false;
            }

            if (cmbStatus.SelectedItem == null)
            {
                MessageBox.Show("请选择状态", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbStatus.Focus();
                return false;
            }

            return true;
        }

        private bool SaveUser()
        {
            if (!ValidateInput()) return false;

            try
            {
                var user = new PUser
                {
                    UserId = txtUserId.Text.Trim(),
                    UserName = txtUserName.Text.Trim(),
                    Password = txtPassword.Text.Trim(),
                    IDCardNo = txtIDCardNo.Text.Trim(),
                    Permissionvalue = ((PermissionItem)cmbPermission.SelectedItem).Value,
                    UserStatus = cmbStatus.SelectedItem.ToString()
                };

                if (currentUser == null) // 新增
                {
                    // 检查用户ID是否已存在
                    if (allUsers.Any(u => u.UserId == user.UserId))
                    {
                        MessageBox.Show("用户ID已存在，请使用其他ID", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtUserId.Focus();
                        return false;
                    }

                    bool result = repository.Insert(user);
                    if (result)
                    {
                        allUsers = repository.GetList<PUser>(); // 重新加载用户列表
                        MessageBox.Show("用户添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("用户添加失败，请稍后重试", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
                else // 编辑
                {
                    // await repository.UpdateUserAsync(user);
                    var existingUser = allUsers.FirstOrDefault(u => u.UserId == user.UserId);
                    if (existingUser != null)
                    {
                        existingUser.UserName = user.UserName;
                        existingUser.Password = user.Password;
                        existingUser.IDCardNo = user.IDCardNo;
                        existingUser.Permissionvalue = user.Permissionvalue;
                        existingUser.UserStatus = user.UserStatus;
                    }
                    //更新到数据库中
                    bool result = repository.Update(existingUser);
                    if (result)
                    {
                        allUsers = repository.GetList<PUser>(); // 重新加载用户列表
                    }
                    else
                    {
                        MessageBox.Show("用户更新失败，请稍后重试", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }

                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存用户失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        #region 事件处理

        private void dgvUsers_SelectionChanged(object sender, EventArgs e)
        {
            if (!isEditing)
            {
                btnEdit.Enabled = dgvUsers.SelectedRows.Count > 0;
                btnDelete.Enabled = dgvUsers.SelectedRows.Count > 0;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            SetFormMode(FormMode.Add);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvUsers.SelectedRows.Count > 0)
            {
                var selectedUserId = dgvUsers.SelectedRows[0].Cells["UserId"].Value.ToString();
                var user = allUsers.FirstOrDefault(u => u.UserId == selectedUserId);
                if (user != null)
                {
                    LoadUserToEdit(user);
                    SetFormMode(FormMode.Edit);
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvUsers.SelectedRows.Count > 0)
            {
                var selectedUserId = dgvUsers.SelectedRows[0].Cells["UserId"].Value.ToString();
                var result = MessageBox.Show($"确定要删除用户 '{selectedUserId}' 吗？", "确认删除",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    try
                    {
                        bool result2 = repository.Delete<PUser>(d => d.UserId == selectedUserId) > 0;
                        if (result2)
                        {
                            LoadUsers();
                            MessageBox.Show("用户删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"删除用户失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (SaveUser())
            {
                LoadUsers();
                SetFormMode(FormMode.View);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            SetFormMode(FormMode.View);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchUsers();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            txtSearchUserId.Text = "";
            txtSearchUserName.Text = "";
            cmbSearchPermission.SelectedIndex = -1;
            cmbSearchStatus.SelectedIndex = -1;
            LoadUsers();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadUsers();
        }

        #endregion
    }

    public enum FormMode
    {
        View,
        Add,
        Edit
    }

    public class PermissionItem
    {
        public string Text { get; set; }
        public long Value { get; set; }
    }
}